from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.views import APIView, Response
from rest_framework.generics import GenericAPIView
import random
# 导入序列化器
from . import serializers

from meiduo_mall.libs.captcha.captcha import captcha
from . import constants
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code


import logging
logger = logging.getLogger('django')

# Create your views here.
# 本视图中实现验证环节

# GenericAPIView增加了操作序列化器(serializer_class)和数据库查询(queryset)的方法
# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id = xxx&text=xxx
class SMSCodeView(GenericAPIView):  # View:自己写所有逻辑　　　APIView:写的东西一样　　　GenericAPIView（增加了序列化器，可以校验）:将校验部分放在序列化器里边
    # 操作序列化器
    serializer_class = serializers.ImageCodeCheckSerializer
    # 发短信需要获得手机号,uuid,前端输入的图片验证码
    def get(self, request, mobile): # mobile满足正则就能进来，不用校验
        # 创建序列化器对象
        # DRF中使用request.query_params来获得？后的数据，类似于django的一键多值的查询
        serializer = self.get_serializer(data = request.query_params)
        # 校验
        serializer.is_valid(raise_exception=True)

        # 校验通过就发送短信
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 99999)
        logger.info(sms_code)
        redis_conn = get_redis_connection('verify_codes')
        # 保存短信验证码
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()

        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, ms_code_expires], 1)
        send_sms_code.delay(mobile, sms_code)
        print('手机号：', mobile)
        # ccp.send_template_sms(mobile, [sms_code, ms_code_expires], 1)
        return Response({'message': 'OK'})

# 实现图片验证码的生成
class ImageCodeView(APIView):
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        logger.info(text)
        redis_conn = get_redis_connection('verify_codes')
        try:
            redis_conn.set('img_%s' % image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES) # set存字符串，过期时间
            print('图片验证码写入成功')
        except Exception as e:
            logger.error('写入redis二号库异常')
            print('图片验证码写入redis二号库异常')
        return HttpResponse(image, content_type='image/jpg')